import { each } from "lodash";
import React, { useState, useEffect, useMemo } from "react";
import { RendererPropTypes } from "@/visualizations/prop-types";
import resizeObserver from "@/services/resizeObserver";
import getChartData, { getParameter, getScheme } from "../getChartData";
import { prepareCustomChartData, createCustomChartRenderer } from "../plotly";
import $ from "jquery";

export default function CustomPlotlyChart({ Plotly, options, data, row, onClickHandler, onRefreshDashboardHandler, onRefreshWidgetHandler, onExpandDashboardHandler }) {
  const [container, setContainer] = useState(null);
  const [customCode, setCustomCode] = useState(options.customCode);

  const renderCustomChart = useMemo(() => createCustomChartRenderer(customCode, options.enableConsoleLogs), [
    customCode,
    options.enableConsoleLogs,
  ]);

  const plotlyData = useMemo(() => prepareCustomChartData(getChartData(data.rows, options)), [options, data]);
  const showPortal = window.location.search.includes("show_portal") && localStorage.getItem('colorstyle_mode');

  function getXColumn(options) {
    var result = 'value';
    each(options.columnMapping, (type, column) => {
      if (type === "x") {
        result = column;
        return false;
      }
    });          
    return result;
  }
  
  function getClickColumn(options) {
    var result;
    
    if (options.hasOwnProperty("clickColumn")) {
      result = options.clickColumn;
    } else {
      each(options.columnMapping, (type, column) => {
        if (type === "clickColumn") {
          result = column;
          return false;
        }
      });     
    }

    return result;
  }

  useEffect(() => {
    if (container) {
      const unwatch = resizeObserver(container, () => {

        // Clear existing data with blank data for succeeding codeCall adds data to existing plot.
        Plotly.purge(container);

        const scheme = getScheme(showPortal);
        const parameter = getParameter();

        require.ensure([], function(require) {
          import(/* webpackChunkName:"echarts-gl" */ 'echarts-gl');    
        }, 'echarts-gl');
        require.ensure([], function(require) {
          import(/* webpackChunkName:"echarts" */ 'echarts').then((echarts) => {    
            if (!window.$) window.$ = $;

            try {
              renderCustomChart(data && data.rows, plotlyData.x, plotlyData.ys, container, scheme, parameter, Plotly, echarts, $,
                row || (data && data.rows && data.rows.length>0 && data.rows[0]), 
                options.clickEnabled ? onClickHandler : ()=>{}, 
                onRefreshDashboardHandler, onRefreshWidgetHandler, onExpandDashboardHandler);
            } catch (err) {
              if (options.enableConsoleLogs) console.log(`自定义视图错误: ${err}`); // eslint-disable-line no-console
            }  
          });
        }, 'echarts');

        if (options.clickEnabled && !!onClickHandler && typeof container.on === "function") {
          container.on('plotly_click', currentData => {
            try {
              var key = getXColumn(options);
              var value =  currentData.points[0].x || currentData.points[0].label;

              let clickColumn = getClickColumn(options);
              if (!!clickColumn && !!data.rows) {
                each(data.rows, row => {
                  if (row.hasOwnProperty(clickColumn)) {
                    var is_equal = false;
                    if (row[key] === value)  is_equal = true;
                    if (!is_equal) {
                      if (row[key].toString() === value.toString()) is_equal = true;
                    }
                    if (!is_equal) {
                      if (row[key].hasOwnProperty('_isAMomentObject') && row[key]._isAMomentObject) {
                        if (row[key].format('YYYY-MM-DD HH:mm:ss') === value.toString()) 
                          is_equal = true;
                        else if (new Date(row[key].format()).getTime() == new Date(value.toString()).getTime())
                          is_equal = true;
                      }
                    }
                    if (is_equal) {
                      key = clickColumn;
                      value = row[key].toString();
                      return false;
                    }
                  }
                })
              }

              if (!!options.clickParameter) key = options.clickParameter;

              let obj = {};
              obj[key] = value;
              onClickHandler(obj);
            } catch (error) {
              console.log(`自定义图表错误: ${error}`);
            }
          });
        }
      });
      return unwatch;
    }
  }, [Plotly, container, plotlyData, renderCustomChart, options, data, onClickHandler, onRefreshDashboardHandler, onRefreshWidgetHandler, onExpandDashboardHandler]);

  // Cleanup when component destroyed
  useEffect(() => {
    if (container) {
      return () => Plotly.purge(container)
    }
  }, [Plotly, container]);

  return <div className="chart-visualization-container" ref={setContainer} 
    style={showPortal ? {background:"#00000000", color: localStorage.getItem('colorstyle_color')} : null} />;
}

CustomPlotlyChart.propTypes = RendererPropTypes;
